using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Territory DAL/DTO object
	/// </summary>
	public static partial class TerritoryExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Territory item, TerritoryDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Territory DTO cannot be null.");
			if (item == null) throw new Exception("The Territory item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			dr["TerritoryID"] = dtoItem.TerritoryId;
			dr["TerritoryDescription"] = dtoItem.TerritoryDescription;
			dr["RegionID"] = dtoItem.RegionId;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="territoryCollection">The source DAL collection.</param>
		public static void Fill(this List<TerritoryDTO> list, TerritoryCollection territoryCollection)
		{
			if (territoryCollection == null) throw new Exception("The Territory collection cannot be null.");
			if (list == null) list = new List<TerritoryDTO>();
			foreach (Territory item in territoryCollection)
			{
				TerritoryDTO newItem = new TerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this TerritoryDTO dtoItem, Territory item)
		{
			if (dtoItem == null) throw new Exception("The Territory DTO cannot be null.");
			if (item == null) throw new Exception("The Territory item cannot be null.");
			dtoItem.TerritoryId = item.TerritoryId;
			dtoItem.TerritoryDescription = item.TerritoryDescription;
			dtoItem.RegionId = item.RegionId;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<TerritoryDTO> list)
		{
			if (list == null) list = new List<TerritoryDTO>();
			TerritoryCollection retval = TerritoryCollection.RunSelect();
			foreach (Territory item in retval)
			{
				TerritoryDTO newItem = new TerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<TerritoryDTO> list, Expression<Func<TerritoryQuery, bool>> where)
		{
			if (list == null) list = new List<TerritoryDTO>();
			list.Fill(TerritoryCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<TerritoryDTO> RunSelect(this List<TerritoryDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<TerritoryDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Territory.FieldNameConstants sortField;
			try
			{
				sortField = (Territory.FieldNameConstants)Enum.Parse(typeof(Territory.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<TerritoryDTO> retVal = new PagedQueryResults<TerritoryDTO>();
			TerritoryPaging paging = new TerritoryPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new TerritoryPagingFieldItem(sortField, ascending));

			TerritoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = TerritoryCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Territory");
				dalList = (TerritoryCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<TerritoryDTO>();
			foreach (Territory item in dalList)
			{
				TerritoryDTO newItem = new TerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<TerritoryDTO> list, string linq)
		{
			if (list == null) list = new List<TerritoryDTO>();

			TerritoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = TerritoryCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Territory");
				dalList = (TerritoryCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<TerritoryDTO>();
			foreach (Territory item in dalList)
			{
				TerritoryDTO newItem = new TerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static TerritoryDTO Persist(this TerritoryDTO territory)
		{
			if (territory == null) throw new Exception("The Territory DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Territory newItem = null;
			TerritoryCollection newCollection = null;

			bool isIdentityChecked = false;
			if (false) {}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Territory.SelectUsingPK(territory.TerritoryId);
				if (newItem == null)
				{
					newCollection = new TerritoryCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(territory);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			territory.Fill(newItem);
			return territory;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<TerritoryDTO> territoryList)
		{
			if (territoryList == null) throw new Exception("The Territory DTO list cannot be null.");
			//Get all objects from the database that match PK
			TerritoryCollection territoryCollection = new TerritoryCollection();
			List<TerritoryPrimaryKey> keyList = new List<TerritoryPrimaryKey>();
			foreach (TerritoryDTO dto in territoryList)
			{
				keyList.Add(new TerritoryPrimaryKey(dto.TerritoryId));
			}			
			territoryCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.TerritorySelectByPks(keyList));
			territoryCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (TerritoryDTO dto in territoryList)
			{
				Territory territory = (from x in (IEnumerable<Territory>)territoryCollection
					where x.TerritoryId == dto.TerritoryId
					select x).FirstOrDefault();

				if (territory == null) territory = territoryCollection.NewItem();
				territory.Fill(dto);
				if (!territory.IsParented) territoryCollection.AddItem(territory);
			}
			territoryCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<TerritoryDTO> deletedList = new List<TerritoryDTO>();
			foreach (TerritoryDTO dto in territoryList)
			{
				Territory territory = (from x in (IEnumerable<Territory>)territoryCollection
					where x.TerritoryId == dto.TerritoryId
					select x).FirstOrDefault();

				if (territory != null) dto.Fill(territory);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (TerritoryDTO dto in deletedList)
			{
				territoryList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Territory Select by Column

		#endregion

		#region Territory SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this TerritoryDTO territory, string territoryid)
		{
			Territory item = ACME.Northwind.Business.Objects.Territory.SelectUsingPK(territoryid);
			if (item == null) return false;
			territory.Fill(item);
			return true;
		}

		#endregion

		#region Territory Select By Foreign Key

		/// <summary>
		/// Populate a 'Region' DTO object collection from its relationship with the 'Territory' table.
		/// </summary>
		public static void SelectByRegion(this List<TerritoryDTO> TerritoryList, int regionid)
		{
			TerritoryCollection list = TerritoryCollection.RunSelect(x => x.RegionId == regionid);
			foreach (Territory item in list)
			{
				TerritoryDTO newItem = new TerritoryDTO();
				newItem.Fill(item);
				TerritoryList.Add(newItem);
			}
		}

		#endregion

		#region Territory Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this TerritoryDTO territory)
		{
			Territory item = ACME.Northwind.Business.Objects.Territory.SelectUsingPK(territory.TerritoryId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
